<template>
  <div class="flex flex-col">
    <!-- 子抽屉 -->
    <a-modal :title="title" :visible="visible" @ok="createAction"
      @cancel="rollback(1)" :width="680" :ok-text="$t('user.verification-code.required1166')"
      :cancel-text="$t('user.email.required11')">
      <a-form :form="form" labelAlign="right" :forceRender="true">
        <!-- 这个部分是隐藏的数据 -->
        <a-form-item label="ID" class="hidden">
          <a-input v-decorator="['Id']" />
        </a-form-item>
        <a-form-item label="DpiaQid" class="hidden">
          <a-input v-decorator="['DpiaQid']" />
        </a-form-item>
        <!-- 这个部分是隐藏的 -->
        <a-form-item style="margin: 0;" label="合规要求编号:">
          <a-input v-decorator="['DpiaActionIdTag']" style="width: 615px;" disabled />
        </a-form-item>
        <a-form-item style="margin: 0;" :label="$t('user.verification-code.required11156617233')">
          <a-input v-decorator="['DpiaActionName', { rules: [{ required: true, message: $t('user.verification-code.required111566110577324') }] }]"
            :placeholder="$t('user.verification-code.required111566172')" style="width: 615px;" :disabled="state == 'see' || caDisable">
          </a-input>
          <!-- <a-input style="width: 400px;margin-right: 20px;"  :placeholder="$t('user.verification-code.required111566172')" :value="selectedValue"  ></a-input> -->
          <!-- <a-select
                :placeholder="$t('user.verification-code.required111566110577181')" style="width: 200px;" @change="templateSelection" v-decorator="['DpiaActionName', { rules: [{ required: true, message: 'APPID需要选择!' }] }]">
                <a-select-option v-for="item in templateId" :value="item.value" :key="item.value">
                  {{ item.label }}
                </a-select-option>
            </a-select>   -->
        </a-form-item>
        <a-form-item style="margin: 0;" :label="$t('user.verification-code.required111566173')">
          <a-textarea :auto-size="{ minRows: 3, maxRows: 10 }"
            :placeholder="$t('user.verification-code.required11156617311')" :rows="3"
            v-decorator="['DpiaActionInfo', { rules: [{ required: true, message: $t('user.verification-code.required111566110577281') }] }]"
            style="width: 615px;" :disabled="state == 'see' || caDisable"/>
        </a-form-item>
        <a-row>
          <!-- 负责人、时间组合 -->
          <a-col :span="12">
            <a-form-item :label="$t('user.verification-code.required111566174')">
              <a-select v-decorator="['DpiaActionUserId', { rules: [{ required: true, message: $t('user.verification-code.required11156611057737144228143122244') }] }]"
              :placeholder="$t('user.verification-code.required111566175')" show-search option-filter-prop="children"
                        :default-active-first-option="false" v-model="inputValue" @search="filte1rOption" :showArrow="false"
                        :filterOption="false" style="width: 300px">
                <a-select-option v-for="item in userList" :value="item.value" :key="item.value">
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('user.login.message-invalid-verification-code0011')" v-if="state == 'see' || mode">
              <a-select v-decorator="['DpiaActionStatus', { rules: [{ required: true,
                 message: $t('user.verification-code.required111566110577280333') }] }]"
                :placeholder="$t('user.login.message-invalid-verification-code0011')" style="width: 300px;">
                <a-select-option v-for="item in statusList" :value="item.value" :key="item.value">
                  {{$t(item.label)}}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-item :label="$t('user.verification-code.required111566170')">
              <a-date-picker v-decorator="['DpiaActionFinishTime']" format="YYYY-MM-DD" style="width: 300px;" :placeholder="$t('user.verification-code.required111566157')" :disabled-date="disabledDate"/>
            </a-form-item>
          </a-col> -->
        </a-row>
        <!-- <a-row> -->
        <!-- 对象组合 -->
        <!-- <a-col :span="12">
            <a-form-item :label="$t( 'user.verification-code.required111566174')">
              <a-select v-decorator="['DpiaActionUserId', { rules: [{ required: true, message: $t(  'user.verification-code.required111566110577280')}] }]"
                :placeholder="$t( 'user.verification-code.required111566174')" style="width: 300px">
                <a-select-option v-for="item in userList" :value="item.value" :key="item.value">
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col> -->
        <!-- <a-col :span="12">
            <a-form-item :label="$t('user.verification-code.required111566176')">
              <a-select v-decorator="['DpiaActionDcoId']"
                :placeholder="$t('user.verification-code.required111566130')" style="width: 300px">
                <a-select-option v-for="item in userList" :value="item.value" :key="item.value">
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col> -->
        <!-- </a-row> -->

        <!-- 备注的timeline -->
        <a-form-item label="法律法规详细来源">
          <a-timeline>
            <a-timeline-item v-for="(item, index) in inputList" :key="item.index">
              <!-- 操作按钮 -->
              <a-space size="0" align="center">
                <p style="min-width: 150px;"> {{ item.actionCreateUser || userinfo.name }} {{ item.actionCreateTime }}</p>
                <a-button v-if="item.editable === false" type="link" @click="editInput(item, index)">{{
                  $t('user.verification-code.required111566147') }}</a-button>
                <a-button v-if="item.editable === true && state != 'see'" type="link" @click="okInput(item, index)" >{{
                  $t('user.verification-code.required1166') }}</a-button>
                <a-button type="link" @click="deleteInput(item)" v-if="state != 'see'">{{ $t('app.setting.copy') }}</a-button>
              </a-space>
              <a-form-item>
                <a-textarea :auto-size="{ minRows: 3, maxRows: 10 }"
                  :rows="3" :disabled="!item.editable"
                  v-model="item.value" />
              </a-form-item>
            </a-timeline-item>
            <!-- 备注的新增 -->
            <a-button style="float: right;" @click="addInput" :disabled="state == 'see'">{{ $t('user.verification-code.required1115661814455')
            }}</a-button>
          </a-timeline>
        </a-form-item>
        <a-upload :multiple="true" 
        accept=".png, .jpg, .jpeg, .gif, .txt, .pdf, .doc,
         .docx, .xlsx, .xls, .ppt, .pptx, .vsd, .vsdx, .vssx, .vstx, .vsdm, .vssm, .vstm, .zip, .tar, .rar, .msg"
        :remove="delFile" :file-list="fileLists" :customRequest="handleChange" :disabled="state == 'see' || caDisable">
          <a-button>
            <a-icon type="upload" />
            落地要求示例和验收标准示例
          </a-button>
        </a-upload>
        <a-form-item :label="$t('user.verification-code.required111566180234')" style="margin-top: 10px;"
          v-if="false">
          <a-textarea v-decorator="['DpiaActionResult']"
            :placeholder="$t('user.verification-code.required11156618011667788')" :rows="3" style="width: 670px" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>


<script>
import { userQuery } from '@/api/common/form'
import { ristCreateAction, ristDelActionRemark, RISKEditActionList, ristDelAction } from '@/api/risk/form'
import { ristCreateActionRemark, ristEditActionRemark } from '@/api/risk/json'
import { dpiaRemarkLists, FilesDel, templateSelection, templateSelectionInfo } from '@/api/dpia/form'
import axios from 'axios'
import moment from 'moment'
import { getUserList } from '@/api/common/form';
import storage from "store";
import {ACCESS_TOKEN} from "@/store/mutation-types";

export default {
  props: {
    questionId: {
      type: String
    },
    chapterId: {
      type: Number
    }
  },
  components: {
  },
  data() {
    return {
      inputValue:'',
      timerId: '',
      keyword:'',
      // 创建DPIA问卷状态
      createQuestionStatus: false,
      // 默认不传ID
      types: false,
      // 下面这些都是通用的
      form: this.$form.createForm(this),
      // 主体状态
      visible: false,
      // 上传文件列表
      fileLists: [],
      // 上传所需的信息
      env: process.env.VUE_APP_BASE_API,
      // 备注列表
      inputList: [],
      // Action的ID
      actionId: "",
      selectedValue: '',
      inputhtml: '',
      // 用户下拉列表
      userList: [],
      // 状态下拉 
      statusList: [
        {
          'label': 'user.verification-code.required111566133',
          'value': 1
        },
        {
          'label': 'user.verification-code.required1115661455555',
          'value': 3
        },
        {
          'label':'user.v172',
          'value': 4
        },
        {
          'label': 'user.verification-code.required111566110577371442281431222335566555555',
          'value': 5
        },
      ],
      // 备注用的信息
      actionCreateUser: "",
      actionCreateUserId: "",
      //区分是整体评估还是查看
      state: '',
      title: undefined,
      //
      // templateId: []
      mode: false,
      userinfo: this.$store.state.user.info,
      caDisable: false
    }
  },
  watch:{
    async inputValue(value){
        const { data } = await getUserList({ UserEmail: value,UserName:value })
        this.userList = [
            ...data,
            {
                label: "Ma weiwei",
                value: "Ma weiwei" 
            },
            {
                label: "Lin yutang",
                value: "Lin yutang" 
            },
        ]
    }
  },
  methods: {
    // 用户查询
    async filte1rOption(value) {
      this.inputValue = value
      // if (event.key === 'Enter'|| event.keyCode === 13){
      //   const value = event.target.value;
      //   const { data } = await getUserList({ UserEmail: value,UserName:value })
      //   this.userList = data
      //   console.log("search:", this.userList)
      // }
    },
    // handleSelectChange(value) {
    //   this.selectedValue = value;
    // },
    disabledDate(current) {
      const currentDate = moment().format('YYYY-MM-DD');
      return current && current.format('YYYY-MM-DD') < currentDate;
    },
    async open(id, state, mode) {
      this.state = state
      this.mode = mode
      //模版选择ID
      //  const {data:templateId } = await templateSelection()
      //  this.templateId = templateId
      // 清空数据
      this.form.resetFields()

      // 获取下拉用户列表
    //   const { data: userList } = await userQuery(1);
    //   this.userList = userList

      // 打开弹窗
      this.visible = true;

      // 初始化数据
      this.fileLists = []
      this.inputList = []
      // this.selectedValue='',
      await this.$nextTick();

      if (id == undefined) {
        this.title = this.$t('user.verification-code.required1115661105768')
        // this.selectedValue='';
        // 新建走这个
        // 初始化RISK的Action，不带risk的ID
        const { data } = await ristCreateAction({ DpiaQid: this.questionId });
        this.form.setFieldsValue({
          DpiaActionIdTag: data.DpiaActionIdTag,
          DpiaQid: this.questionId,
          DpiaActionUserId:data.DpiaActionUserResponsible,
          Id: data.Id
        })

        // 赋值
        this.actionId = data.Id;

        // 保留创建时间、创建人信息
        this.actionCreateUser = data.DpiaActionCreateUser;
        this.actionCreateUserId = data.DpiaActionCreateUserId;

        // 创建备注列表初始化
        this.addInput()
      } else {
        // 编辑走这个
        this.title = this.$t('user.verification-code.required11156611057688')
        const { data } = await RISKEditActionList({ Id: id });
        // this.selectedValue=data.DpiaActionName;
        // data.DpiaActionFinishTime = data.DpiaActionFinishTime ? moment(data.DpiaActionFinishTime, 'YYYY-MM-DD HH:mm:ss') : null;
        console.log(this.userinfo.YtId )
        console.log( data.DpiaActionDcoId)
        
        console.log( data.DpiaActionUserId)
        console.log(this.userinfo.YtAdminName)
        if(
          data.DpiaActionStatus === 5 && (
            data.DpiaActionDcoId !== this.userinfo.YtId ||
            data.DpiaActionUserId === this.userinfo.YtAdminName
          )
        ) {
          this.caDisable = true
        }
        this.userList.push({
          value:data.DpiaActionUserId,
          label:data.DpiaActionUserResponsible,
        })
        this.form.setFieldsValue(data);
        const { data: remarkLists } = await dpiaRemarkLists({ ActionId: id, ActionType: 1 })

        // 保留创建时间、创建人信息
        this.actionCreateUser = data.DpiaActionCreateUser;
        this.actionCreateUserId = data.DpiaActionCreateUserId;

        // 赋值
        this.actionId = data.Id;

        if (remarkLists.length > 0) {
          for (var i = 0; i < remarkLists.length; i++) {
            // 创建备注列表初始化
            this.inputList.push({
              value: remarkLists[i].ActionRemarkInfo,
              editable: false,
              actionCreateTime: remarkLists[i].ActionCreatetime,
              actionCreateUser: remarkLists[i].ActionCreateUserName,
              actionCreateUserId: remarkLists[i].ActionCreateUser,
              Id:remarkLists[i].Id
            });
          }
        }

        this.addInput();
        const { data: fileLists } = await dpiaRemarkLists({ ActionId: id, ActionType: 2 })
        if (fileLists.length > 0) {
          for (var i = 0; i < fileLists.length; i++) {
            // 上传的文件处理
            var fileName = fileLists[i].ActionUploadUrl.split("/")
            this.fileLists.push({
              uid: i,
              name: fileName[fileName.length - 1],
              status: "done",
              url: fileLists[i].ActionUploadUrl,
              fileId:fileLists[i].Id
            })
          }
        }
      }
    },
    createAction() {
      // 执行创建action
      const {
        form: { validateFields },
      } = this
      // 按钮loading
      this.loading = true
      // validateFields 是校验form表单数据 
      // force: true 是默认所有字段都校验
      // values 表单的值 
      validateFields({ force: true }, async (err, values) => {
        if (!err) {
          try {
            for (var i = 0; i < this.userList.length; i++) {
              if (this.userList[i].value == values.DpiaActionUserId) {
                values.DpiaActionUserResponsible = this.userList[i].label
               
              }
            }
            values.DpiaActionUserId = values.DpiaActionUserId.replaceAll('/', '#@%$')
            // for (var i = 0; i < this.userList.length; i++) {
            //   if (this.userList[i].value == values.DpiaActionDcoId) {
            //     values.DpiaActionDcoReview = this.userList[i].label
            //   }
            // }
            // 时间格式化
            // values.DpiaActionFinishTime = moment(values.DpiaActionFinishTime).format('YYYY-MM-DD')
            const params = { ...values }
            await ristCreateAction({ DpiaChapterId: this.chapterId, ...values });
            if(this.state=='edit'){
              this.$emit('succeed')
            }else{
              this.$emit('succeed','action')
            }
            this.$message.success(this.$t( 'user.verification-code.required111566110577308'))
            //如果成功就关闭
            this.rollback(0)
          } catch (error) {
            console.log('err', error)
            this.$message.error(error)
          } finally {
            this.loading = false
          }
        } else {
          setTimeout(() => {
            this.loading = false
          }, 600)
        }
      })
    },
    async rollback(type) {
      // 处理关闭弹窗
      if (this.visible) {
        this.visible = false;
        if(this.state !== "edit" && type === 1) {
          await ristDelAction({Id: this.actionId})
        }
      } else {
        this.visible = true;
      }
    },
    async editInput(item, index) {
      // 打开备注编辑能力
      item.editable = true
    },
    async deleteInput(item) {
      // 删除备注
      try {
        if (Object.keys(item).indexOf("Id") != -1) {
          // 防止ID被初始化
          if (item.Id != 0) {
            await ristDelActionRemark({ Id: item.Id })
          }
        }
        // 在列表里也删除
        this.inputList.splice(this.inputList.indexOf(item), 1);
      } catch (error) {
        console.log("error:", error)
        this.$message.error(error)
      }
    },
    async okInput(item, index1) {
      // 备注提交信息保存
      item.editable = false
      if (Object.keys(item).indexOf("Id") != -1) {
        // 更新
        const { data } = await ristEditActionRemark([{
          Id: item.Id, ActionRemarkInfo: item.value, ActionId: this.actionId, ActionType: 1
        }])
        item.actionCreateTime = data.ActionUpdatetime
      } else {
        // 新增
        const { data } = await ristCreateActionRemark([{
          ActionRemarkInfo: item.value, ActionId: this.actionId, ActionType: 1
        }])
        // 赋值
        item.Id = data.Id
        item.actionCreateTime = data.ActionCreatetime
      }
    },
    addInput() {
      // 新增备注
      var objData = new Date();
      var year = objData.getFullYear();
      var month = objData.getMonth() + 1;
      var day = objData.getDate();
      if (objData.getSeconds() < 10) {
        var seconds = '0' + objData.getSeconds();
      } else {
        var seconds = objData.getSeconds();
      }
      if (objData.getMinutes() < 10) {
        var miuntes = '0' + objData.getMinutes();
      } else {
        var miuntes = objData.getMinutes();
      }
      if (objData.getHours() < 10) {
        var hours = '0' + objData.getHours();
      } else {
        var hours = objData.getHours();
      }
      if (month < 10) {
        month = '0' + month;
      }
      if (day < 10) {
        day = '0' + day
      }
      // 新增一个新的数据初始化
      this.inputList.push({
        value: "",
        editable: true,
        actionCreateTime: year + "-" + month + "-" + day + " " + hours + ":" + miuntes + ":" + seconds,
        actionCreateUser: this.actionCreateUser,
        actionCreateUserId: this.actionCreateUserId
      });
    },
    async handleChange(e) {
      // 上传提交
      this.uploadLoading = true
      let formdata = new FormData()
      formdata.append('file', e.file)
      try {
        const { status, data } = await axios({
          url: `${this.env}/v1/oss/upload`,
          method: 'post',
          data: formdata,
          headers: {
            token: storage.get(ACCESS_TOKEN),
            tokens:storage.get("bmwToken") || "",
          },
        })
        if (status == 200 && data.code == 1) {
          if (data.data != "") {
            await this.$nextTick()
            var files = data.data;
            var index = this.fileLists.length;
            if (files != "" && files != undefined) {
              var fileName = files.split("/")
              // 上传文件完成后新增
              // 新增
              const fileId = await ristCreateActionRemark([{
                ActionUploadUrl: data.data, ActionId: this.actionId, ActionType: 2
              }])
              this.fileLists.push({
                uid: index + 1,
                name: fileName[fileName.length - 1],
                status: "done",
                url: data.Url+data.data,
                fileId: fileId.data.Id
              })
            }
          }
        } else {
          this.$message.error(this.$t('user.verification-code.required111566110577282'))
        }
      } catch (error) {
        console.log(error)
        this.$message.error(error)
      } finally {
        this.uploadLoading = false
      }
    },
    //删除上传文件
    async delFile(file) {
      console.log('1');
      console.log('file', file);
      const index = this.fileLists.indexOf(file);
      this.fileLists.splice(index, 1);
      await FilesDel({Id:file.fileId})
      return true;
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    // async templateSelection(value){
    // const {data} = await templateSelectionInfo({DpiaActionId: value})
    // console.log('data--------------!!!!!!!!!!!!!!!!',data);
    // // this.selectedValue = data.ActionId;
    // console.log(value);
    // await this.$nextTick()
    // this.form.setFieldsValue({
    //       // DpiaActionIdTag: data.DpiaActionIdTag,
    //       DpiaActionName:data.ActionName,
    //       DpiaActionInfo: data.ActionInfo,
    //       // DpiaActionStatus: data.ActionStatus != 0 ? data.ActionStatus : undefined ,
    //       DpiaActionFinishTime: data.ActionFinishTime? moment(data.ActionFinishTime, 'YYYY-MM-DD') : undefined,
    //       DpiaActionUserId: data.ActionUserId,
    //       // DpiaActionDcoId: data.ActionDcoId,
    //       DpiaActionResult: data.ActionResult
    //     })
    // }
  },
}
</script> 
<style lang="less" scoped>
/deep/.ant-drawer-body {
  height: 800px !important;
}

.ant-pagination {
  float: right;
}

/deep/.ant-timeline-item-content {
  top: -11px;
}

/deep/.ant-timeline-item {
  padding: 0 0 1px;
}

/deep/.ant-form-item {
  margin-bottom: 0px;
}

/deep/.ant-space-align-center {
  align-items: center;
  margin-left: 230px;
}

/deep/.ant-space-align-center {
  align-items: center;
  margin-left: 0 !important;
}</style>